package com.gz.logistics.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.gz.logistics.R;
import com.gz.logistics.adapter.HomeOrderAdapter;
import com.gz.logistics.app.Define;
import com.gz.logistics.app.MipcaActivityCapture;
import com.gz.logistics.app.OrderDetailActivity;
import com.gz.logistics.library.IAuthor;
import com.gz.logistics.library.IOrder;
import com.gz.logistics.library.listener.BatchOrdersStatusSignListener;
import com.gz.logistics.library.listener.HomeOrderListener;
import com.gz.logistics.library.pojo.OrderInfo;
import com.gz.logistics.library.pojo.UserInfo;
import com.gz.logistics.library.util.Constants;
import com.gz.logistics.library.util.CrashHandler;
import com.gz.logistics.library.util.PreferenceModel;
import com.gz.logistics.util.ToastUtils;
import com.gz.logistics.widget.LoadingCover;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;


import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;


public  class HomeFragment extends Fragment implements
        LoadingCover.OnLoadingCoverRefreshListener,
        View.OnClickListener, AdapterView.OnItemClickListener,
        PullToRefreshBase.OnRefreshListener {
    private String TAG = HomeFragment.class.getSimpleName();
    private View mConvertView;
    private ImageView iv_actionbar_QRCode;
    private TextView  tv_actionbar_deliveryName;
    private ImageView iv_all_select;
    private TextView tv_all_confirm;
    private TextView tv_logistic_confirm;
    private TextView tv_delivery_confirm;
    private PullToRefreshListView mPullListView;
    private LoadingCover mLoadingCover;
    private Context mContext;
    private Dialog mLoadingData;

    private List<String> SelectedOrderNumbers;// 存放被选中的订单编号
    private List<OrderInfo> mDataList;
    private boolean isAllSelected = false; // 是否全部被选中
    private boolean atLeastOneIsSelected ; // 至少有一个订单被选中则为true
    private MyUpdataUI updataUI;
    private HomeOrderAdapter mAdapter;
    private MyHomeOrderListener mHomeOrderlistener;
    private MyBatchOrdersStatusSignListener myBatchOrdersStatusSignListener;
    private boolean isSelectLogisticBtn = true;//默认选中 物流待确认订单
    private int BUTTON_LOGISTIC = 1;//1 代表”物流“按钮
    private int BUTTON_DELIVERY = 2;//2 代表”业务“按钮
    private int THE_BUTTON_TO_BE = -1;// 将要切换到的按钮 1 代表”物流“按钮 2 代表”业务“按钮 ; 切换成功后，即表示切换后，所选中的按钮
                                      //切换失败后值为-1
    private UserInfo userInfo;
    private RefreshReceiver mRefreshReceiver;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mRefreshReceiver = new RefreshReceiver();
        IntentFilter filter = new IntentFilter(Define.ACTION_REFRESH_HOME);
        getActivity().registerReceiver(mRefreshReceiver,filter);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mConvertView == null){
            mConvertView = inflater.inflate(R.layout.fragment_home,container,false);
            init();
        }
        mDataList = new ArrayList<OrderInfo>();
        updataUI = new MyUpdataUI(this);
        mAdapter = new HomeOrderAdapter(mDataList,mContext,updataUI);
        mPullListView.setAdapter(mAdapter);
        initListener();
        loadData();
        return mConvertView;

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ((ViewGroup)mConvertView.getParent()).removeView(mConvertView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        updataUI.release();;
        mHomeOrderlistener.release();
        myBatchOrdersStatusSignListener.release();
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }


    /**
     * 各种界面空间的点击事件
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_all_select:
                OnClickAllSelectedBuutton();
                break;
            case R.id.tv_logistic_confirm:
               if (isSelectLogisticBtn){
                   return ;
               }else{
                   THE_BUTTON_TO_BE = BUTTON_LOGISTIC;
                   mLoadingData.show();
                   loadData();
                   //mPullListView.setRefreshing();
               }
                break;
            case R.id.tv_delivery_confirm:
               if (!isSelectLogisticBtn){
                   return ;
               }else{
                   THE_BUTTON_TO_BE = BUTTON_DELIVERY;
                   mLoadingData.show();
                   loadData();
                   //mPullListView.setRefreshing();
               }
                break;
            case R.id.tv_all_confirm:

                 batchOrdersSign();
                break;
            case R.id.iv_actionbar_QRCoder:
                Intent intent = new Intent();
                intent.setClass(mContext,MipcaActivityCapture.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 网络异常的情况下，会显示一个cover 覆盖整个屏幕
     * 可以通过点击该cover 再次请求网络
     */
    @Override
    public void onLoadingCoverRefresh() {
        loadData();
    }




    /**
     * 点击listview item 执行该方法
     * @param adapterView
     * @param view
     * @param i  position
     * @param l id
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (l < 0){
            return ;
        }
        OrderInfo clickItem = mDataList.get((int)l);
        if (clickItem != null){
            Intent intent = new Intent();
            intent.setClass(mContext, OrderDetailActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("clickOrder",clickItem);
            intent.putExtras(bundle);
            startActivityForResult(intent, Define.ACTIVITY_CODE_ORDER_DETAIL);
        }


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Define.ACTIVITY_CODE_ORDER_DETAIL && resultCode == Define.ACTIVITY_CODE_ORDER_DETAI_CHANGE){
            if (data != null){ // 如果订单详情界面做了修改，则把该订单从当前列表中删除，然后刷新界面，否则什么也不做

//                OrderInfo tempInfo = null;
//                String changedSn = data.getStringExtra("changedOrderSn");
//                for(OrderInfo temp : mDataList){
//                    if (temp.getSn().equals(changedSn)){
//                        tempInfo = temp;
//                        break;
//                    }
//                }
//
//                if (tempInfo != null){
//                    mDataList.remove(tempInfo);
//                    mAdapter.notifyDataSetChanged();
//                }
                loadData();

            }
        }

    }

    /**
     * listview 下拉刷新执行该方法
     * @param refreshView
     */
    @Override
    public void onRefresh(PullToRefreshBase refreshView) {
        loadData();
    }

    /**
     *     初始化控件
     */
    private void init() {
        mContext = getActivity().getApplicationContext();
        userInfo = IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));
        mPullListView = (PullToRefreshListView) mConvertView.findViewById(R.id.list);
        iv_actionbar_QRCode = (ImageView) mConvertView.findViewById(R.id.iv_actionbar_QRCoder);
        tv_actionbar_deliveryName = (TextView) mConvertView.findViewById(R.id.tv_actionbar_deliveryName);
        iv_all_select = (ImageView) mConvertView.findViewById(R.id.iv_all_select);
        tv_all_confirm = (TextView) mConvertView.findViewById(R.id.tv_all_confirm);
        tv_logistic_confirm = (TextView) mConvertView.findViewById(R.id.tv_logistic_confirm);
        tv_delivery_confirm = (TextView) mConvertView.findViewById(R.id.tv_delivery_confirm);
        mLoadingCover = (LoadingCover) mConvertView.findViewById(R.id.layout_loading_cover);

        mLoadingData = new Dialog(getActivity(),R.style.DialogTheme);
        mLoadingData.setContentView(R.layout.loading_data_dialog2);
        mLoadingData.setCanceledOnTouchOutside(false);
        mLoadingData.setCancelable(false);


        mLoadingCover.setOnLoadingCoverRefreshListener(this);

        iv_actionbar_QRCode.setOnClickListener(this);
        iv_all_select.setOnClickListener(this);
        tv_all_confirm.setOnClickListener(this);
        tv_logistic_confirm.setOnClickListener(this);
        tv_delivery_confirm.setOnClickListener(this);


        mPullListView.setOnRefreshListener(this);
        mPullListView.setOnItemClickListener(this);
        if (userInfo != null){
            tv_actionbar_deliveryName.setText("配送员："+userInfo.getUser_name());
        }

    }



    /**
     * 每次选择某个订单条目，都会执行该方法 判断是否需要更新主界面的全选按钮
     */
    public void CheckIsAllSelect(){
        isAllSelected = true;
        atLeastOneIsSelected = false;
        // 循环遍历所有订单
        for (int i = 0 ; i < mDataList.size() ; i++){
            OrderInfo info  = mDataList.get(i);
            if (! info.isSelected()){
                isAllSelected = false; // 存在一个订单为 未选中状态

            }else{
                atLeastOneIsSelected = true ;// 有一个订单是选中状态
            }
        }
        // 如果订单列表为空
        if (mDataList.size() == 0){
            isAllSelected = false;
            atLeastOneIsSelected = false;
        }
        // 如果 订单列表全都选中了，则把全选复选框置为选中状态，否则置为没选中状态
        if (isAllSelected){
            iv_all_select.setBackgroundResource(R.mipmap.ic_shopping_selected);
        }else{
            iv_all_select.setBackgroundResource(R.mipmap.ic_shopping_unselected);
        }
         // 如果至少有一个订单被选中，那么把“整体确认”置为可见 ; 否则置为不可见
        if (atLeastOneIsSelected){

            tv_all_confirm.setVisibility(View.VISIBLE);

        }else{
            tv_all_confirm.setVisibility(View.INVISIBLE);
        }

    }

    /**
     * 点击 “整体确认”后 执行的
     */
    public void batchOrdersSign() {
        mLoadingData.show();
        if (mDataList.size() == 0){
            mLoadingData.dismiss();
            ToastUtils.showToast(mContext,"订单列表为空");
            return;
        }

        // 循环遍历找到所有选中的订单
        ArrayList<String> sellectedOrdes = new ArrayList<String>();
        for (int i = 0 ; i < mDataList.size() ; i ++ ){
            OrderInfo info = mDataList.get(i);
            if (info.isSelected()){
                sellectedOrdes.add(info.getSn());
            }
        }

        if (sellectedOrdes.size() <= 0){
            mLoadingData.dismiss();
            ToastUtils.showToast(mContext, "请先选择订单");
            return ;
        }else{
            // 把选中的订单编号拼成以逗号隔开的字符串
            StringBuilder str = new StringBuilder("");
            for (int j = 0 ; j < sellectedOrdes.size() ; j ++){
                if (j == 0 ){
                    str.append(sellectedOrdes.get(j));
                    CrashHandler.i(TAG,"第0个订单的编号="+sellectedOrdes.get(j));
                } else{
                    CrashHandler.i(TAG, "第" + j + "个订单的编号=" + sellectedOrdes.get(j));
                    str.append(","+sellectedOrdes.get(j));
                }
            }
            if (str != null && !(str.toString().equals(""))){
                if (isSelectLogisticBtn){
                    IOrder.getInstance().batchOrdersLogisticsStatusSign(str.toString(),myBatchOrdersStatusSignListener);
                }else{
                    CrashHandler.i(TAG,"str="+str.toString());
                    IOrder.getInstance().batchOrdersDeliveryStatusSign(str.toString(),myBatchOrdersStatusSignListener);
                }
            }else{
                mLoadingData.dismiss();
            }

        }
    }

    /**
     * 点击主界面的全选按钮触发事件
     */
    public void OnClickAllSelectedBuutton(){
        if (isAllSelected){ // 如果点击之前复选框是选中状态，则循环遍历置把所有订单置为未选中状态
            for (int i = 0 ; i < mDataList.size() ; i++){
                OrderInfo info = mDataList.get(i);
                info.setIsSelected(false);
            }
            isAllSelected = false;
        }else{  // 如果点击之前复选框是未选中状态，则循环遍历置把所有订单置为选中状态
            for (int i = 0 ; i < mDataList.size() ; i ++){
                OrderInfo info  = mDataList.get(i);
                info.setIsSelected(true);
            }
            isAllSelected = true;
        }
        if (isAllSelected){ //如果订单被全部选中，把全选复选框置为选中，“整体确认” 按钮置为可见
            iv_all_select.setBackgroundResource(R.mipmap.ic_shopping_selected);
            tv_all_confirm.setVisibility(View.VISIBLE);
        }else{//如果订单全部未选中，把全选复选框置为未选中，“整体确认” 按钮置为不可见
            iv_all_select.setBackgroundResource(R.mipmap.ic_shopping_unselected);
            tv_all_confirm.setVisibility(View.INVISIBLE);
        }
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 初始化回调接口
     */
    public void initListener(){
        mHomeOrderlistener = new MyHomeOrderListener(this);
        myBatchOrdersStatusSignListener = new MyBatchOrdersStatusSignListener(this);
        iv_actionbar_QRCode.setOnClickListener(this);

    }

    /**
     * 响应成功后执行的方法   ，主要是修改 button 的状态，重置isSelectLogisticBtn 的状态 ，刷新全选按钮和列表
     * onNoDistribute  onNoConditionSatisfiedOrder  onDataError 均为响应成功，只是返回的数据类型不同
     * @param orderInfoList
     */
    private void afterOnResponseSuccess(List<OrderInfo> orderInfoList) {

        if (THE_BUTTON_TO_BE == BUTTON_LOGISTIC) { // 如果是将要切换到 物流待确认 界面
            isSelectLogisticBtn = true;
            tv_logistic_confirm.setBackgroundResource(R.drawable.selector_register_btn);
            tv_logistic_confirm.setTextColor(getResources().getColor(R.color.white));
            tv_delivery_confirm.setBackgroundResource(R.drawable.shape_no_confirm_tv_default);
            tv_delivery_confirm.setTextColor(getResources().getColor(R.color.RGB_333333));
        } else if (THE_BUTTON_TO_BE == BUTTON_DELIVERY) {  // 如果是将要切换到 也为待确认 界面
            isSelectLogisticBtn = false;
            tv_logistic_confirm.setBackgroundResource(R.drawable.shape_no_confirm_tv_default);
            tv_logistic_confirm.setTextColor(getResources().getColor(R.color.RGB_333333));
            tv_delivery_confirm.setBackgroundResource(R.drawable.selector_register_btn);
            tv_delivery_confirm.setTextColor(getResources().getColor(R.color.white));
        }
        mDataList.clear();
        mDataList.addAll(orderInfoList);
        mAdapter.notifyDataSetChanged();
        CheckIsAllSelect(); // 判断选中状态
        mLoadingCover.onRefreshSuccess();

        if (mPullListView.isRefreshing()) {
            mPullListView.getLoadingLayoutProxy().refreshSuccess();
        }
        if (mLoadingData.isShowing()) {
            mLoadingData.dismiss();
        }
    }


    /**
     * 加载数据
     */
    public void loadData(){
        if (THE_BUTTON_TO_BE > 0 && THE_BUTTON_TO_BE == BUTTON_LOGISTIC){
            // 如果即将要切换到 ”物流“ 状态
            IOrder.getInstance().getHomeOrder(Define.FLAG_TRANS_STATUS_NO_SIGN,Define.FLAG_DELEVERY_STATUS_ALL,mHomeOrderlistener);
        }else if (THE_BUTTON_TO_BE > 0 && THE_BUTTON_TO_BE == BUTTON_DELIVERY){
            // 如果即将要切换到 ”业务“状态
            IOrder.getInstance().getHomeOrder(Define.FLAG_TRANS_STATUS_SIGNED,Define.FLAG_DELEVERY_STATUS_NO_SIGN,mHomeOrderlistener);
        }else if (THE_BUTTON_TO_BE  < 0){
            if (isSelectLogisticBtn){
                IOrder.getInstance().getHomeOrder(Define.FLAG_TRANS_STATUS_NO_SIGN,Define.FLAG_DELEVERY_STATUS_ALL,mHomeOrderlistener);
            }else{
                IOrder.getInstance().getHomeOrder(Define.FLAG_TRANS_STATUS_SIGNED,Define.FLAG_DELEVERY_STATUS_NO_SIGN,mHomeOrderlistener);
            }
        }

    }

    /**
     * 界面更新回调接口
     */
    private static class MyUpdataUI implements HomeOrderAdapter.UpdataUI{
        private HomeFragment mOuter;

        public MyUpdataUI(HomeFragment mOuter) {
            this.mOuter = mOuter;
        }
        public void release(){
            new WeakReference<HomeFragment>(mOuter);
        }
        @Override
        public void updata() {
            mOuter.CheckIsAllSelect();
        }
    }

    /**
     * 首页订单加载回调接口
     */
    private static class  MyHomeOrderListener extends HomeOrderListener{
        private HomeFragment mOuter;

        public MyHomeOrderListener(HomeFragment mOuter) {
            this.mOuter = mOuter;
        }
        public void release(){
            new WeakReference<HomeFragment>(mOuter);
        }
        @Override
        public void onNoNetWork() {
            if (mOuter.mPullListView.isRefreshing()){
                mOuter.mPullListView.getLoadingLayoutProxy().refreshFailed();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            mOuter.THE_BUTTON_TO_BE = -1;
            mOuter.mLoadingCover.onRefreshFailed(Define.MSG_NO_NETWORK);
            ToastUtils.showToast(mOuter.getActivity(),Define.MSG_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            mOuter.mLoadingCover.onRefreshFailed();
            if (mOuter.mPullListView.isRefreshing()){
                mOuter.mPullListView.getLoadingLayoutProxy().refreshFailed();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter.getActivity(),"加载失败");
            mOuter.THE_BUTTON_TO_BE = -1;

        }

        @Override
        public void onResponseSuccess(List<OrderInfo> orderInfoList) {

            mOuter.afterOnResponseSuccess(orderInfoList);

        }

        @Override
        public void onNoDistribute() {
            mOuter.afterOnResponseSuccess(new ArrayList<OrderInfo>());
            ToastUtils.showToast(mOuter.getActivity(), "还未分配到派送订单");
        }

        @Override
        public void onNoConditionSatisfiedOrder() {
            mOuter.afterOnResponseSuccess(new ArrayList<OrderInfo>());
            ToastUtils.showToast(mOuter.mContext, "没有满足条件的订单");
        }

        @Override
        public void onDataError() {
            mOuter.afterOnResponseSuccess(new ArrayList<OrderInfo>());
            ToastUtils.showToast(mOuter.mContext,"数据异常");

        }

    }

    /**
     * 批量物流签收回调接口
     */
    private static class MyBatchOrdersStatusSignListener extends BatchOrdersStatusSignListener {
        private HomeFragment mOuter;

        public MyBatchOrdersStatusSignListener(HomeFragment mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<HomeFragment>(mOuter);
        }

        @Override
        public void onPartOrdersFail() {
              mOuter.loadData();
              mOuter.mLoadingData.dismiss();
            if (mOuter.isSelectLogisticBtn){
                ToastUtils.showToast(mOuter.mContext,"存在物流未签收订单");
            }else{
                ToastUtils.showToast(mOuter.mContext,"存在业务未签收订单");
            }




        }

        @Override
        public void onResponseSuccess() {
            mOuter.loadData();
            mOuter.mLoadingData.dismiss();
            if (mOuter.isSelectLogisticBtn){
                ToastUtils.showToast(mOuter.mContext,"整体物流签收成功");
            }else{
                ToastUtils.showToast(mOuter.mContext,"整体业务签收成功");
            }

        }

        @Override
        public void onExistOrdersHasNotSignLogistics() {
            mOuter.loadData();
            mOuter.mLoadingData.dismiss();
            if (mOuter.isSelectLogisticBtn) {
                ToastUtils.showToast(mOuter.mContext, "存在还未进行物流签收的订单");
            }

        }

        @Override
        public void onDataError() {
            mOuter.loadData();
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.mContext, "数据错误");

        }

        @Override
        public void onNoNetWork() {
            mOuter.mLoadingData.dismiss();
            ToastUtils.showToast(mOuter.mContext, Define.MSG_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            mOuter.loadData();
            mOuter.mLoadingData.dismiss();
            if (mOuter.isSelectLogisticBtn){
                ToastUtils.showToast(mOuter.mContext,"整体物流签收失败");
            }else{
                ToastUtils.showToast(mOuter.mContext,"整体业务签收失败");
            }


        }
    }

    private class RefreshReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            loadData();
        }
    }
}
